python

您所在的位置:网站首页 python turtle 导入图片 python

python

#python| 来源: 网络整理| 查看: 265

这是我的代码:

from tkinter import * import turtle as t import random bob=Tk() t.setup(width = 200,height = 200) t.bgpic(picname="snakesandladders.gif") def left(event): t.begin_fill() print("left") t.left(90) def right(event): print("right") t.right(90) def forward(event): print("forward") t.forward(100) block = Frame(bob, width=300, height=250) bob.bind("", left) bob.bind("", right) bob.bind("", forward) block.pack() bob.mainloop()

我的错误是:

Traceback (most recent call last): File "/Users/lolszva/Documents/test game.py", line 6, in t.bgpic(picname="snakesandladders.gif") File "", line 8, in bgpic File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/turtle.py", line 1481, in bgpic self._bgpics[picname] = self._image(picname) File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/turtle.py", line 479, in _image return TK.PhotoImage(file=filename) File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/tkinter/__init__.py", line 3545, in __init__ Image.__init__(self, 'photo', name, cnf, master, **kw) File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/tkinter/__init__.py", line 3501, in __init__ self.tk.call(('image', 'create', imgtype, name,) + options) _tkinter.TclError: couldn't open "snakesandladders.gif": no such file or directory

我是初学者,所以我真的不知道我是否没有导入库。在另一个类似的问题中,bgpic() 不起作用,它说将图片转换为 gif,但对我来说它仍然不起作用。我使用的是 Mac OSX Python 版本 3.8.0。

最佳答案

虽然您的问题是缺少 GIF 文件,但即使该文件存在并且位于正确的目录中,您的程序仍然会失败。

第二个问题是您在 tkinter 上调用独立的 turtle 。您可以独立运行turtle,它设置底层tkinter根和窗口,也可以在tkinter中嵌入运行turtle,您可以在其中设置turtle的根和 Canvas 漫游。但是在您创建的 tkinter 根上调用独立的 turtle 将会失败并出现错误:

... self.tk.call(_flatten((self._w, cmd)) + self._options(cnf)) _tkinter.TclError: image "pyimage2" doesn't exist

以下是如何在独立 turtle 中实现您的程序:

from turtle import Screen, Turtle def left(): turtle.left(90) def right(): turtle.right(90) def forward(): turtle.forward(100) screen = Screen() screen.setup(width=200, height=200) screen.bgpic(picname="snakesandladders.gif") screen.onkey(left, "a") screen.onkey(right, 'd') screen.onkey(forward, 'w') turtle = Turtle() screen.listen() screen.mainloop()

将 GIF 背景图像放在与源代码相同的目录中。

如果您想在 turtle Canvas 旁边添加 tkinter 小部件,则只需要嵌入 turtle 。请参阅 RawTurtle 和 TurtleScreen 的文档。

与 forward() 距离相比,您的窗口尺寸较小 - 您可能需要调整其中之一。

关于python - 我将图片转换为 GIF 但 turtle 的 bgpic() 仍然无法正常工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58460292/



【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3